import { IFolder, IStore, logger } from '@coremail/mail_base';
import { HashMap } from '@kit.ArkTS';

export class FolderIdUtil {
  private static currentId: number = 1;

  private static folderIdMapper: HashMap<string, number> = new HashMap<string, number>();

  public static parseFolderToID(folder: IFolder): number {
    const keyOfFolder = folder.getFullName();
    return FolderIdUtil.getFoldId(keyOfFolder);
  }

  public static getFoldId(folderFullPath: string): number {
    if (!folderFullPath) {
      logger.log(`parseFolderToID`, `folder doesn't have a full name!folderFullPath:${folderFullPath}`);
      return -2;
    }
    if (FolderIdUtil.folderIdMapper.hasKey(folderFullPath)) {
      return FolderIdUtil.folderIdMapper.get(folderFullPath);
    } else {
      FolderIdUtil.currentId++;
      const newKey = FolderIdUtil.currentId
      FolderIdUtil.folderIdMapper.set(folderFullPath, newKey);
      return newKey;
    }
  }

  public static getFatherFoldId(foldFullPath: string, store: IStore): number {
    if (!foldFullPath) {
      logger.log(`parseFolderToID`, `folder doesn't have a full name!folder info:${foldFullPath}`);
      return -2;
    }

    const delimiter = store.getDelimiter(true)
    // const delimiter = '.'
    const result: string[] = foldFullPath.split(delimiter);
    if (result.length === 1) {
      return -1;
    } else if (result.length > 1) {
      const fatherFoldFullPath = foldFullPath.substring(0, foldFullPath.lastIndexOf(delimiter));
      return this.getFoldId(fatherFoldFullPath);
    } else {
      logger.log(`getFatherFoldId`, `error while in get father folder id,folder:${foldFullPath},store:${store}`);
      return -2;
    }
  }

  public static parseFatherFoldId(folder: IFolder, store: IStore): number {
    const keyOfFolder = folder.getFullName();
    return FolderIdUtil.getFatherFoldId(keyOfFolder, store);
  }

  public static findFolderNameById(folderId: number): string {
    let folderPath: string | null = null;
    FolderIdUtil.folderIdMapper.forEach((value, key) => {
      if (value === folderId) {
        folderPath = key;
      }
    })
    return folderPath
  }

  public static reset() {
    FolderIdUtil.currentId = 1;
    FolderIdUtil.folderIdMapper.clear();
  }
}